package thread;

import java.util.LinkedList;
import java.util.Queue;

/**
 * wait 与 notify 的demo
 *
 * 使用消费者生产者 练习  有四个坑
 *
 *
 * wait 阻塞方法
 * notify 唤醒wait
 *
 * @Author zb
 * @Date 2022/3/23 14:50
 */
public class WaitNotifyDemo {

    private static final int MAX_LEN = 10;
    private static Queue<Integer> queue = new LinkedList<Integer>();
    private static Runnable product = new Runnable() {
        @Override
        public void run() {
            while (true){
                synchronized (queue){
                    if(queue.size() == MAX_LEN){
                        queue.notify();
//                        System.out.println("队列已满，生产者停止生产");
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        queue.add(1);
                    }
                }
            }
        }
    };

    private static Runnable consume = new Runnable() {
        @Override
        public void run() {
            while (true){
                synchronized (queue){
                    if(queue.size() == 0){
                        queue.notify();
//                        System.out.println("队列已空，生产者停止消费");
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else{
                        queue.poll();
                    }
                }
            }
        }
    };

    public static void main(String[] args){

        Thread productor = new Thread(product);
        productor.start();
        Thread consumer = new Thread(consume);
        consumer.start();

        Thread monitor = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        System.out.println(queue.size());
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        monitor.start();
    }

}
